package com.lindenvalley.de;



import java.io.StringWriter;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lindenvalley.de.content.Section;
import com.lindenvalley.de.content.response.Response;
import com.lindenvalley.de.content.response.ResponseQuestion;
import com.lindenvalley.de.content.response.ResponseRound;
import com.lindenvalley.de.content.response.ResponseSection;
import com.lindenvalley.de.content.user.User;
import com.lindenvalley.de.database.DbSectionsHelper;
import com.lindenvalley.de.network.WorkServer;

public class SignActivity extends Activity {

	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	private EditText loginView, passwordView;
	private CheckBox rememberMeView;
	private MyTouchListener listener;
	private TextView registerView, anmeldenView;
	private LoginAsyncTask task;
	private SharedPreferences preferences;
	private static final String PREFERENCE_LOGIN = "login";
	private static final String PREFERENCE_PASSWORD = "password";
	private final String[] columns = new String[]{DbSectionsHelper.ROUND, DbSectionsHelper.QUESTION, DbSectionsHelper.ANSWER_TYPE, DbSectionsHelper.DATE};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		loginView = (EditText) findViewById(R.id.loginView);
		passwordView = (EditText) findViewById(R.id.passwordView);
		rememberMeView = (CheckBox) findViewById(R.id.loginRememberBox);
		registerView = (TextView) findViewById(R.id.loginRegister);
		anmeldenView = (TextView) findViewById(R.id.loginAnmelden);
		listener = new MyTouchListener();
		registerView.setOnTouchListener(listener);
		anmeldenView.setOnTouchListener(listener);
		preferences = getPreferences(Activity.MODE_PRIVATE);		
	}
	
	class MyTouchListener implements View.OnTouchListener{

		/* (non-Javadoc)
		 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
		 */
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			int id = v.getId();
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				switch (id) {
				case R.id.loginRegister:
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_registeren)));
					startActivity(intent);
					break;
				case R.id.loginAnmelden:
					String userNameString = loginView.getText().toString();
					String passwordString = passwordView.getText().toString();					
					String[] params = new String[2];
//					params[0] = userNameString;
//					params[1] = passwordString;
					params[0] = "tester@tester.com";
					params[1] = "tester";

					task = new LoginAsyncTask();
					task.execute(params, null, null);
					break;
				}
				return true;
			} else
				return false;
		}
		
	}
	
	class LoginAsyncTask extends AsyncTask<Object, Object, Object>{

		ProgressDialog dialog;
		boolean isCancel = false;
		String[] parameters;
		SQLiteDatabase database;
		StringWriter writer = new StringWriter();
		Serializer serializer = new Persister();

		
		@Override
		protected void onProgressUpdate(Object... values){
			String value = (String) values[0];
			dialog.setMessage(value);
		}
		
		@Override
		protected void onPreExecute (){
			dialog = new ProgressDialog(SignActivity.this);
			dialog.setMessage("Connecting....");						
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					isCancel = true;
				}
			});
			dialog.show();
			
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			parameters = (String[]) params[0];
			Object result;
			// Login to server
			result = WorkServer.getInstance().doLogin(parameters[0], parameters[1]);
			// synch learning and exam data from server
			if (result instanceof User && ((User)result).getCode() == User.CODE_SUCCESS){
				publishProgress("Synchronization....");
				DbSectionsHelper sectionsHelper = new DbSectionsHelper(SignActivity.this);
				database = sectionsHelper.getReadableDatabase();
				Cursor cursor = database.query(DbSectionsHelper.TABLE_NAME, new String[]{"distinct theme_id"}, null, null, null, null, null);
				Response response = new Response();
				int isExam = 0;				
				getResponseData(cursor, response, isExam);
				sendResponseData(response, ((User)result).getUserId(), isExam);
				if (response.getSections() != null)
					response.getSections().clear();
				isExam = 1;

				//Synchronization data for exam
				isExam = 1;				
				getResponseData(cursor, response, isExam);
				sendResponseData(response, ((User)result).getUserId(), isExam);
				
				cursor.close();
				database.close();
				

			}
			return result;
		}
		
		private void sendResponseData(Response response, int userId, int isExam){
			try {
				serializer.write(response, writer);
				//Send data to server (learning)
				String synchData = null;
				Log.i("SEND TO SERVER", writer.toString());
				if (isExam == 0)
					synchData = (String) WorkServer.getInstance().synchLearingData(writer.toString(), userId);
				if (isExam == 1)
					synchData = (String) WorkServer.getInstance().synchExamData(writer.toString(), userId);
				// Write data to local DB
				if (synchData != null && synchData.length() > 0){
					Log.i("<---------------", synchData);
					if (response.getSections() != null)
						response.getSections().clear();
					serializer.read(response, synchData);
					writeDataToDatabase(response, isExam);						
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		private void getResponseData(Cursor cursor, Response response, int isExam){
			// Get data for synch (learning)
			if (cursor.getCount() > 0){
				cursor.moveToFirst();					
				do{
					int sectionId = cursor.getInt(0);
					Section sectionTheme = WorkServer.getInstance().getSections().getSectionById(sectionId);
					int questionSize = 0;
					if (sectionTheme != null && sectionTheme.getQuestion() != null)
						questionSize = sectionTheme.getQuestion().size();
					Cursor sectionCursor = null;
					//Выборка для обучения
					if (isExam == 0){
					sectionCursor = database.query(
							DbSectionsHelper.TABLE_NAME, //Table name
							columns, //column
//							DbSectionsHelper.THEME_ID + "=? and (select max(round) from section where theme_id=? ) > round and " + DbSectionsHelper.IS_EXAM + "=" + isExam, //where 
//							DbSectionsHelper.THEME_ID + "=? and (select count(*) from section s2 where theme_id=s1.theme_id and round=s1.round) =?  and " + DbSectionsHelper.IS_EXAM + "=" + isExam, //where
							DbSectionsHelper.THEME_ID + "=? and " + DbSectionsHelper.IS_EXAM + "=" + isExam, //where
							new String[]{String.valueOf(sectionId)}, // where args
							null, //group by
							null, //having
							DbSectionsHelper.ROUND); // order by
					} else {
						//Выборка для экзаменов
						sectionCursor = database.query(
								DbSectionsHelper.TABLE_NAME, //Table name
								columns, //column
								DbSectionsHelper.THEME_ID + "=? and " + DbSectionsHelper.IS_EXAM + "=" + isExam, //where 
								new String[]{String.valueOf(sectionId)}, // where args
								null, //group by
								null, //having
								DbSectionsHelper.ROUND); // order by

					}
					if (sectionCursor.getCount() > 0){
						ResponseSection section = new ResponseSection();
						section.setSectionId(sectionId);
						sectionCursor.moveToFirst();
						int currentRound = sectionCursor.getInt(0);
						ResponseRound round = new ResponseRound();
						round.setRoundId(currentRound);
						section.addRound(round);
						do{
							int rnd = sectionCursor.getInt(0);
							if (currentRound != rnd){								
								round = new ResponseRound();
								currentRound = rnd;
								round.setRoundId(currentRound);
								section.addRound(round);
							}
							ResponseQuestion question = new ResponseQuestion();
							question.setQuestionId(sectionCursor.getInt(1));
							question.setAnswerType(sectionCursor.getInt(2));
							question.setDate(sectionCursor.getLong(3));
							round.addQuestion(question);
							
						} while(sectionCursor.moveToNext());
						if (isExam == 0 && round.getQuestions() != null && round.getQuestions().size() != questionSize)
							section.getRounds().remove(section.getRounds().size()-1);
						response.addSection(section);
					}
					sectionCursor.close();
				} while(cursor.moveToNext());
			}
		}
		
		private void writeDataToDatabase(Response response, int isExam){
			ContentValues values = new ContentValues();
			for(ResponseSection section: response.getSections()){
				int sectionId = section.getSectiond();
				if (section.getRounds() != null){
					Cursor maxRoundCursor = database.rawQuery("select max(round) from " + DbSectionsHelper.TABLE_NAME + " where " + DbSectionsHelper.THEME_ID + "=?", new String[]{String.valueOf(section.getSectiond())});
					int roundId = 0;
					if (maxRoundCursor.getCount() >0){
						maxRoundCursor.moveToFirst();
						roundId = maxRoundCursor.getInt(0);
					}
					maxRoundCursor.close();
					for(ResponseRound round: section.getRounds()){
						roundId++;
						if (round.getQuestions() != null){
							for(ResponseQuestion question: round.getQuestions()){
								int answerTYpe = question.getAnswerType();
								int questionId = question.getQuestionId();
								long date = question.getDate();
								values.clear();
								values.put(DbSectionsHelper.ANSWER_TYPE, answerTYpe);
								values.put(DbSectionsHelper.QUESTION, questionId);
								values.put(DbSectionsHelper.DATE, date);
								values.put(DbSectionsHelper.ROUND, roundId);
								values.put(DbSectionsHelper.THEME_ID, sectionId);
								values.put(DbSectionsHelper.IS_EXAM, isExam);
								database.insert(DbSectionsHelper.TABLE_NAME, null, values);
							}
						}
					}
				}
			}
		}
		
		@Override 
		protected void onPostExecute(Object result) {
	         if (dialog != null && dialog.isShowing()){
	        	 dialog.dismiss();
	         }
	        	 
	         if (!isCancel){
	        	 if ((result instanceof String && WorkServer.DENY_VALUE.equals(result)) || (result instanceof User && ((User)result).getCode() == User.CODE_DENY)){
	        		 Toast.makeText(SignActivity.this, R.string.InvalidLogin, Toast.LENGTH_LONG).show();
	        	 } else  if (result instanceof String && WorkServer.NOT_CONNECT.equals(result)){
	        		 Toast.makeText(SignActivity.this, R.string.NotConnect, Toast.LENGTH_LONG).show();
	        	 } else  if (result instanceof User){
	        		 WorkServer.getInstance().setUser((User)result);
	        		 if (rememberMeView.isChecked()){
	        			 Editor editor = preferences.edit(); 
	        			 editor.putString(PREFERENCE_LOGIN, parameters[0]);
	        			 editor.putString(PREFERENCE_PASSWORD, parameters[1]);
	        			 editor.commit();
	        		 }
	        		 SignActivity.this.finish();
	        	 } else {
	        		 Toast.makeText(SignActivity.this, R.string.NotConnect, Toast.LENGTH_LONG).show();
	        	 }
	         }
		}
		
	}
	
	

}
